﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Public.Ocean.Petrel.Extensions.Stream
{
    public class Formatter
    {
        public string Pack<TData>(Schema<TData> schema, TData data)
        {
            StringBuilder result = new StringBuilder();
            foreach (var entry in schema.Pack(data))
            {
                result.Append(entry.Key + ":" + entry.Value);
                result.Append(Environment.NewLine);
            }
            return result.ToString();
        }

        public void Unpack<TData>(Schema<TData> schema, TData data, string pack)
        {
            var items = new List<KeyValuePair<string, string>>();
            foreach (var line in pack.Replace(Environment.NewLine, "\n").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = line.Split(new[] { ':' }, 2);
                items.Add(new KeyValuePair<string, string>(parts[0], parts[1]));
            }
            schema.Unpack(data, items);
        }
    }
}
